import React, {Component} from "react";
import store from "./store";

export default class Page1 extends Component {
  componentDidMount() {
    // store发生变化之后，执行subscribe的监听函数
    this.unsubscribe = store.subscribe(() => {
      this.forceUpdate();
    });
  }

//   componentWillUnmount() {
//     this.unsubscribe();
//   }

  add = () => {
    // 修改状态 set
    store.dispatch({type: "ADD"});
  };

  add1 = () => {
    setTimeout(() => {
        store.dispatch({type: "ADD", payload: 1});
    }, 1000);
  }

  asyAdd = () => {
    store.dispatch((dispatch, getState) => {
      setTimeout(() => {
        dispatch({type: "ADD", payload: 1});
      }, 1000);
    });
  };

  promiseMinus = () => {
    // store.dispatch(
    //   Promise.resolve({
    //     type: "MINUS",
    //     payload: 100,
    //   })
    // );
  };

  render() {
    return (
      <div>
        <h3>page1</h3>
        <p>{store.getState()}</p>
        <button onClick={this.add}>sync-add</button>
        <button onClick={this.add1}>async1-add</button>
        <button onClick={this.asyAdd}>async2-add</button>
        <button onClick={this.promiseMinus}>promiseAdd</button>
      </div>
    );
  }
}
